package com.yc.ssq.servlet;

import com.google.gson.Gson;
import com.ly.common.bean.Result;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "UploadServlet", value = "/upload.do")
// 文件上传注解
@MultipartConfig
public class UploadServlet extends HttpServlet {

    private SsqBiz biz = new SsqBiz();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        // 接收上传的文件
        Part datafile = request.getPart("datafile");
        // 获取文件名
        String filename = datafile.getSubmittedFileName();
        // 保存文件
        datafile.write("c:/" + filename);

        // 保存数据
        biz.save("c:/" + filename);

        Result result = new Result(1, "文件上传成功!", null);
        // 设值响应类型
        response.setContentType("application/json;charset=utf-8");
        // 将java对象转成json字符串
        String json = new Gson().toJson(result);
        // 想浏览器输出
        response.getWriter().print(json);
    }

}
